import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../../../config/StyleConfig.dart';
import '../../../../../res/HDColors.dart';

typedef ChangedTextCallback<T> = void Function(String value);

/// 措施的可编辑的组件
class StepText extends StatefulWidget {
  /// 文本内容
  String content;

  /// 普通的文字样式
  TextStyle? normalStyle;

  /// 可编辑的文字样式
  TextStyle? editStyle;

  ///输入框是否可编辑，默认false，不可编辑
  bool enabled;

  ///文字改变的回调
  ChangedTextCallback? onChangedText;

  StepText(
      {Key? key,
      required this.content,
      this.onChangedText,
      this.enabled = false,
      this.normalStyle,
      this.editStyle})
      : super(key: key);

  @override
  State<StepText> createState() => _StepTextState();
}

class _StepTextState extends State<StepText> {
  /// 文本输入组件列表
  late List<InlineSpan> textWidgets;

  /// 文本输入的内容
  late List<dynamic> textLists;

  /// 可编辑的文字数据
  late List<String> editStringList;

  @override
  void initState() {
    super.initState();
    // TODO 初始化数据，如果widget已经创建过了，就不会再走这里
    textWidgets = [];
    textLists = [];
    editStringList = [];

    var pattern = RegExp("\\[(\\w|[^x00-xff])*\\]");
    if (widget.content.contains(pattern)) {
      /// 正则判断[]
      widget.content.replaceAllMapped(pattern, (match) {
        String text = widget.content.substring(match.start, match.end);
        editStringList.add(text);
        return text;
      });

      List<String> list = widget.content.split(pattern);
      for (int i = 0; i < list.length; i++) {
        String str = list[i];
        textWidgets.add(setNormalTextSpan(str));
        if (i != list.length - 1) {
          textWidgets.add(setWriteTextSpan(context, editStringList[i]));
        }
      }
    } else {
      textWidgets.add(setNormalTextSpan(widget.content));
    }
  }

  // final logic = Get.put(TextFieldWidthRxLogic());

  @override
  Widget build(BuildContext context) {
    return Text.rich(TextSpan(children: textWidgets));
  }

  /// 创建普通的text
  setNormalTextSpan(String text) {
    textLists.add(text);
    return TextSpan(
        text: text,
        style: widget.normalStyle ??
            const TextStyle(
                fontSize: StyleConfig.fontContentSize16,
                color: HDColors.black,
                fontWeight: FontWeight.w500));
  }

  /// 创建可以点击输入的text
  setWriteTextSpan(BuildContext context, String content) {
    if (content.contains("[]")) {
      content = "";
    } else {
      content = content.substring(1, content.length - 1);
    }

    TextEditingController controller = TextEditingController();
    controller.text = content;
    textLists.add(controller);

    double width = 150;
    if (content.isNotEmpty) {
      width = (content.length + 2) * 15;
    }

    return WidgetSpan(
        child: Container(
            width: width,
            margin: EdgeInsets.only(right: 5, left: 5),
            child: TextField(
                maxLines: 1,
                enabled: widget.enabled,
                controller: controller,
                textAlign: TextAlign.center,
                cursorColor: Colors.red,
                onChanged: (value) {
                  if (widget.onChangedText != null) {
                    StringBuffer string = StringBuffer();
                    for (var item in textLists) {
                      if (item is String) {
                        string.write(item);
                      } else if (item is TextEditingController) {
                        string.write("[${item.text.trim().toString()}]");
                      }
                    }
                    widget.onChangedText!(string.toString());
                  }
                },
                // inputFormatters: [
                //   // TODO 正则限制只能中文，英文字母和数字及_
                //   OnlyInputFormatter()
                // ],
                style: widget.editStyle ??
                    const TextStyle(
                        fontSize: 15,
                        color: HDColors.blue,
                        fontWeight: FontWeight.w500),
                decoration: const InputDecoration(
                    contentPadding: EdgeInsets.only(bottom: 2),
                    isDense: true,
                    enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue)),
                    focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.red))))));
  }
}

// class TextFieldWidthRxLogic extends GetxController {
//   var width = 160.w;
//
//   /// 根据文字计算宽度
//   void calculateWidth(String value){
//     /// 如果输入框不可编辑动态计算一下宽度
//     if (value.isNotEmpty) {
//       width = (value.length + 2) * 25.w;
//     }
//   }
// }

/// 匹配中文，英文字母和数字及_:
// ^[\u4e00-\u9fa5_a-zA-Z0-9]+$
const _regExp = r"^[\u4e00-\u9fa5_a-zA-Z0-9]+$";

class OnlyInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.isNotEmpty) {
      if (RegExp(_regExp).firstMatch(newValue.text) != null) {
        return newValue;
      }
      return oldValue;
    }
    return oldValue;
  }
}
